//消息提示
const msg = (str) => {
    return new Promise((resolve, reject) => {
        uni.showToast({
            title: str,
            icon: "none",
            duration: 2000,
            position: "bottom",
            success: () => {
               setTimeout(()=>{
               				    resolve();
               },2000)
            },
        });
    });
};


// 获取验证码
const verifyPhone = (phone) => {
    let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    // if(!正则对象.test(用户输入的信息)){}
    return reg.test(phone);
}




// 成功提示框
const successToast = (str) => {
    return new Promise((resolve, reject) => {
        uni.showToast({
            title: str,
            icon: "success",
            duration: 2000,
            success: () => {
                resolve();
            },
        });
    });
};

// 显示loading 需要配合hideLoading关闭
const showLoading = (str) => {
    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: str,
            success: () => {
                resolve();
            },
        });
    });
};

// 隐藏loading
const hideLoading = () => {
    return new Promise((resolve, reject) => {
        uni.hideLoading({
            success: () => {
                resolve();
            },
        });
    });
};

//获取缓存
const getStorage = (key, sync = true) => {
    try {
        if (sync) {
            return uni.getStorageSync(key);
        } else {
            let data = "";
            uni.getStorage({
                key: key,
                success: function(res) {
                    data = res.data;
                },
            });
            return data;
        }
    } catch (e) {
        return false;
    }
};

//设置缓存
const setStorage = (key, value, sync = true) => {
    try {
        if (sync) {
            return uni.setStorageSync(key, value);
        } else {
            uni.setStorage({
                key: key,
                data: value,
            });
        }
    } catch (e) {}
};


//移除缓存
const delStorage = (key, sync = true) => {
    try {
        if (sync) {
            return uni.removeStorageSync(key);
        } else {
            uni.removeStorage({
                key: key,
            });
        }
    } catch (e) {
        return false;
    }
};

//清空缓存
const clearStorage = (sync = true) => {
    try {
        if (sync) {
            return uni.clearStorageSync();
        } else {
            uni.clearStorage();
        }
    } catch (e) {
        return false;
    }
};

/**
 *
 * @param {Arr} imgList 传入图片数组 | 单张图片也要传数组perviewImage([url])
 * @param {Number} index 不传默认从第一张开始显示
 *
 */
const perviewImage = (imgList, index) => {
    uni.previewImage({
        current: index,
        urls: imgList,
        indicator: "number",
        success: function(res) {},
        fail: function(err) {
            console.log(err);
        },
    });
};

/**
 * 放入缓存时间
 */
export const setCacheTime = (key, value, seconds) => {
    let nowTime = Date.parse(new Date()) / 1000;
    if (key && value) {
        let expire = nowTime + Number(seconds);
        uni.setStorageSync(key, JSON.stringify(value) + '|' + expire)
        console.log('已经把' + key + '存入缓存,过期时间为' + expire)
    }
};
//获取缓存
export const getCacheTime = (key) => {
    let nowTime = Date.parse(new Date()) / 1000;
    let param = uni.getStorageSync(key);
    console.log("获取到的缓存", param);
    if (param) {
        if (typeof param !== 'string') {
            uni.removeStorageSync(key)
            console.log(key + '缓存已失效')
            return undefined;
        } else {
            // 缓存存在，判断是否过期
            let temp = param.split('|');
            if (!temp[1] || temp[1] <= nowTime) {
                uni.removeStorageSync(key)
                console.log(key + '缓存已失效')
                return undefined;
            } else {
                console.log(JSON.parse(temp[0]), "111")
                return JSON.parse(temp[0]);
            }
        }
    }
};
/**
 * @Description: 获取最近7天的日期数据
 * @Author: LiSuwan
 * @Date: 2023-09-20 16:01:09
 */
const getLastSevenDays = () => {
    // 获取当前日期
    let currentDate = new Date();
    // 创建一个数组来存储最近7天的日期
    let recentDates = [];
    // 循环生成最近7天的日期
    for (let i = 0; i < 7; i++) {
        // 将当前日期推到数组中
        recentDates.push(currentDate.toISOString().slice(0, 10));

        // 将当前日期减去一天
        currentDate.setDate(currentDate.getDate() - 1);
    }
    return recentDates
}

/**
 * @Description: 获取未来7天时间
 * @Author: LiSuwan
 * @Date: 2023-09-20 16:01:09
 */
const getForwardSevenDays = () => {
    // 获取当前日期
    let currentDate = new Date();
    // 创建一个数组来存储最近7天的日期
    let recentDates = [];
    // 循环生成最近7天的日期
    for (let i = 0; i < 7; i++) {
        // 将当前日期推到数组中
        recentDates.push(currentDate.toISOString().slice(0, 10));

        // 将当前日期减去一天
        currentDate.setDate(currentDate.getDate() + 1);
    }
    return recentDates
}



var formatDate = function(date, fmt) {
    var time = new Date(date);
    var o = {
        "M+": time.getMonth() + 1, //月份
        "D+": time.getDate(), //日
        "H+": time.getHours(), //小时
        "m+": time.getMinutes(), //分
        "s+": time.getSeconds(), //秒
        "q+": Math.floor((time.getMonth() + 3) / 3), //季度
        "S": time.getMilliseconds() //毫秒
    };

    if (/(Y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
                .length)));
        }
    }

    return fmt;
}

/**
 * @Description: 获取月份中的每一天
 * @Author: LiSuwan
 * @Date: 2023-09-20 16:45:18
 */
function getDaysInCurrentMonth(year, month) {
    let currentDate = new Date();
    let daysInMonth = new Date(year, month, 0).getDate();
    let days = [];

    for (let day = 1; day <= daysInMonth; day++) {
        days.push({
            value: formatDate(new Date(year, month - 1, day), "YYYY-MM-DD"),
            name: formatDate(new Date(year, month - 1, day), "MM月DD日"),
            dateStr: formatDate(new Date(year, month - 1, day), "DD")
        });
    }


    return days;
}



// 富文本图片自适应宽度
export const setArticleDetailImgSize = function(html) {
    html = html.replace(
        /<img/g,
        '<img style="max-width:100%;height:auto" '
    );
    return html;
};

// ============= 校验身份证号合法性 开始 =============
var checkCode = function(val) {
    var p =
        /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    var parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
    var code = val.substring(17);
    if (p.test(val)) {
        var sum = 0;
        for (var i = 0; i < 17; i++) {
            sum += val[i] * factor[i];
        }
        if (parity[sum % 11] == code.toUpperCase()) {
            return true;
        }
    }
    return false;
};

var checkDate = function(val) {
    var pattern =
        /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/;
    if (pattern.test(val)) {
        var year = val.substring(0, 4);
        var month = val.substring(4, 6);
        var date = val.substring(6, 8);
        var date2 = new Date(year + "-" + month + "-" + date);
        if (date2 && date2.getMonth() == parseInt(month) - 1) {
            return true;
        }
    }
    return false;
};
var checkProv = function(val) {
    var pattern = /^[1-9][0-9]/;
    var provs = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江 ",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北 ",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏 ",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
    };
    if (pattern.test(val)) {
        if (provs[val]) {
            return true;
        }
    }
    return false;
};
/**
 * @Description: 校验身份证号合法性
 * @Author: LiSuwan
 * @Param:{String}:val:身份证号
 * @Date: 2019-12-25 21:01:20
 */
export const checkID = function(val) {
    if (checkCode(val)) {
        var date = val.substring(6, 14);
        if (checkDate(date)) {
            if (checkProv(val.substring(0, 2))) {
                return true;
            }
        }
    }
    return false;
};
// ============= 校验身份证号合法性 结束 =============


// ============= 校验手机号 开始 =============
var regExp = {
    'telPhone': /^((1[3,4,5,6,8,9,7][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/, // 手机号码正则表达式
    'userName': /^[A-Za-z0-9]+$/, // 用户名只能是英文和数字
    'emial': /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/, // 邮箱正则表达式
    'number': /^[0-9]*$/, // 只能是数字
    'passwordLength': /^.{5,18}$/, // 密码长度6-18位
    'loginCode': /^[A-Za-z0-9]{4}$/, // 登录验证码英文和数字4位,
    'chineseCode': /[\u4e00-\u9fa5]/g, // 中文字符匹配正则
    'equipmentTypeName': /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/, // 只能包含中/英文、数字和下划线
    'measuringPointName': /^[\u4e00-\u9fa5a-zA-Z0-9]+$/, // 只能包含中/英文、数字
    'checkExcel': /\.(?:xls|xlsx)$/, // 验证是否为Excel文件
    'systemCheckExcel': /^(10500[01][0-9])$/, // 系统校验Excel文档错误提示码
    'password': /^[a-zA-Z0-9]{4,8}$/, //密码字母或数字 6-14位
    "money": /^(\d+)(.\d{0,2})?$/, //小数点后2位
}

/**
 * @Description: 校验手机号码是否正确
 * @Author: LiSuwan
 * @Date: 2019-08-15 21:48:42
 */
var checkTelphone = function(phone) {
    return regExp.telPhone.test(phone) ? true : false;
};
/**
 * @Description: 校验手机号码
 * @Author: LiSuwan
 * @Param:{String}:phone:手机号码
 * @Date: 2019-12-25 21:01:20
 */

export const checkPhone = function(phone) {
    if (!phone) {
        return false;
    } else if (!checkTelphone(phone)) {
        return false;
    }
    return true;
};
// ============= 校验手机号 结束 =============


// ============= 校验邮箱 开始 =============
/**
 * @Description: 校验邮箱
 * @Author: LiSuwan
 * @Date: 2020-01-07 19:00:27
 */
export const checkEmail = function(emial) {
    if (emial == "") {
        return false;
    } else if (regExp.emial.test(emial) == false) {
        return false;
    }
    return emial;
};
// ============= 校验邮箱 结束 =============










export default {
    setArticleDetailImgSize,
    getDaysInCurrentMonth,
    formatDate,
    getLastSevenDays,
    getForwardSevenDays,
    verifyPhone,
    msg,
    successToast,
    showLoading,
    hideLoading,
    getStorage,
    setStorage,
    delStorage,
    clearStorage,
    perviewImage,
    setCacheTime,
    getCacheTime,
    setArticleDetailImgSize,
    checkID,
    checkPhone,
    checkEmail
}